package com.slofzx.nuoda.evaluation.sysTools.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.slofzx.nuoda.common.dto.CompanyDTO;
import com.slofzx.nuoda.common.dto.DictValueDTO;
import com.slofzx.nuoda.common.feign.DictValueClient;
import com.slofzx.nuoda.common.feign.OfficeClient;
import com.slofzx.nuoda.common.vo.CompanyVO;
import com.slofzx.nuoda.common.vo.DictValueVO;
import com.slofzx.nuoda.evaluation.project.enums.ProductTypeEnum;
import com.slofzx.nuoda.evaluation.sysTools.entity.Cascade;
import com.slofzx.nuoda.evaluation.sysTools.dto.CascadeDTO;
import com.slofzx.nuoda.evaluation.sysTools.vo.CascadeVO;
import com.slofzx.nuoda.evaluation.sysTools.dao.CascadeDAO;
import com.slofzx.nuoda.evaluation.sysTools.service.CascadeService;
import com.slofzx.nuoda.common.enums.CommonResultEnum;
import com.slofzx.nuoda.common.enums.ServiceResult;
import com.slofzx.nuoda.common.service.impl.BaseServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 项目中所用到的上下级关联关系表服务实现类
 *
 * @author nuoda
 * @since 2024-03-22 16:40:09
 */
@Service("cascadeService")
public class CascadeServiceImpl extends BaseServiceImpl implements CascadeService {
    @Resource
    private CascadeDAO cascadeDAO;

    @Resource
    private DictValueClient dictValueClient;

    @Resource
    private OfficeClient officeClient;

    /**
     * 查询多条数据
     *
     * @param dto 数据传递类实例对象
     * @return 对象列表
     */
    @Override
    public List<CascadeVO> queryList(CascadeDTO dto) {
//        List<CompanyVO> parentData = officeClient.queryTreeByCode("DQYT").getData();//查询总条数
//        if (CollectionUtils.isEmpty(parentData)) {
//            return null;
//        }
//        // 实现手动分页
//        List<CompanyVO> childrenData = parentData.get(0).getChildren().stream().filter(f -> !f.getType().equals("research")).collect(Collectors.toList());
//        List<CompanyVO>childrenDataPage= childrenData.stream().skip((dto.getPageNo()-1) * dto.getPageSize()).limit(dto.getPageSize()).collect(Collectors.toList());

        Set<String> hashSet = new HashSet<>();
        hashSet.add("gas-region");
        hashSet.add("oil-region");
        hashSet.add("oil-field");
        DictValueDTO dictValueDTO = new DictValueDTO();
        dictValueDTO.setFilterDictSet(hashSet);
        Map<String, String> childData = dictValueClient.queryList(dictValueDTO).getData()
                .stream().collect(Collectors.toMap(DictValueVO::getCode, DictValueVO::getName));//下级dict的code，名称

        CascadeDTO OilRegionDto = new CascadeDTO();
        OilRegionDto.setType("oil-region");
        List<CascadeVO> OilRegionList = this.cascadeDAO.queryList(OilRegionDto);
        OilRegionList.forEach(i -> i.setName(childData.get(i.getSource())));//用字典表里的name替换SYS_CASCADE存的name
        Map<String, List<CascadeVO>> OilRegionMap = OilRegionList.stream().collect(Collectors.groupingBy(CascadeVO::getParentSource));

        CascadeDTO GasRegionDto = new CascadeDTO();
        GasRegionDto.setType("gas-region");
        List<CascadeVO> GasRegionList = this.cascadeDAO.queryList(GasRegionDto);
        GasRegionList.forEach(i -> i.setName(childData.get(i.getSource())));//用字典表里的name替换SYS_CASCADE存的name
        Map<String, List<CascadeVO>> GasRegionMap = GasRegionList.stream().collect(Collectors.groupingBy(CascadeVO::getParentSource));

        CascadeDTO fieldDto = new CascadeDTO();
        fieldDto.setType("oil-field");
        List<CascadeVO> fieldList = this.cascadeDAO.queryList(fieldDto);
        fieldList.forEach(i -> i.setName(childData.get(i.getSource())));//用字典表里的name替换SYS_CASCADE存的name
        Map<String, List<CascadeVO>> fieldMap = fieldList.stream().collect(Collectors.groupingBy(CascadeVO::getParentSource));

        List<CascadeVO> resultList = new ArrayList(2);
        for (ProductTypeEnum value : ProductTypeEnum.values()) {
            CascadeVO vo = new CascadeVO();
            vo.setSource(value.getId());
            vo.setName(value.getName());
            vo.setOilRegionList(OilRegionMap.get(value.getId()));
            vo.setGasRegionList(GasRegionMap.get(value.getId()));
            vo.setFieldList(fieldMap.get(value.getId()));
            resultList.add(vo);
        }

        return resultList;
    }

    /**
     * 查询多条数据
     *
     * @param dto 数据传递类实例对象
     * @return 对象列表
     */
    @Override
    public List<CascadeVO> queryChildrenList(CascadeDTO dto) {
        DictValueDTO dictValueDTO1 = new DictValueDTO();
        dictValueDTO1.setDictId(dto.getType());
        Map<String, String> childData = dictValueClient.queryList(dictValueDTO1).getData().stream().collect(Collectors.toMap(DictValueVO::getCode, DictValueVO::getName));//下级dic的id，名称
        List<CascadeVO> cascadeVOList = this.cascadeDAO.queryList(dto);
        cascadeVOList.forEach(i -> i.setName(childData.get(i.getSource())));//用字典表里的name替换SYS_CASCADE存的name
        return cascadeVOList;
    }

    /**
     * 修改数据
     *
     * @param dto 实例对象
     * @return 操作结果
     */
    @Override
    @Transactional
    public ServiceResult update(CascadeDTO dto) {
        QueryWrapper<Cascade> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Cascade::getParentSource, dto.getParentSource());
        this.cascadeDAO.delete(queryWrapper);//先删除旧的内容

        if (null != dto.getOilRegionList() && !dto.getOilRegionList().isEmpty()) {
            IntStream.range(0, dto.getOilRegionList().size()).forEach(index -> {
                Cascade cascade = new Cascade();
                cascade.setType("oil-region");
                cascade.setState("region");
                cascade.setSource(dto.getOilRegionList().get(index));
                cascade.setParentSource(dto.getParentSource());
                cascade.setSort(index + 0.0);
                preInsert(cascade);
                this.cascadeDAO.insert(cascade);
            });
        }
        if (null != dto.getGasRegionList() && !dto.getGasRegionList().isEmpty()) {
            IntStream.range(0, dto.getGasRegionList().size()).forEach(index -> {
                Cascade cascade = new Cascade();
                cascade.setType("gas-region");
                cascade.setState("region");
                cascade.setSource(dto.getGasRegionList().get(index));
                cascade.setParentSource(dto.getParentSource());
                cascade.setSort(index + 0.0);
                preInsert(cascade);
                this.cascadeDAO.insert(cascade);
            });
        }
        if (null != dto.getFieldList() && !dto.getFieldList().isEmpty()) {
            IntStream.range(0, dto.getFieldList().size()).forEach(index -> {
                Cascade cascade = new Cascade();
                cascade.setType("oil-field");
                cascade.setState("field");
                cascade.setSource(dto.getFieldList().get(index));
                cascade.setParentSource(dto.getParentSource());
                cascade.setSort(index + 0.0);
                preInsert(cascade);
                this.cascadeDAO.insert(cascade);
            });
        }
        return CommonResultEnum.SUCCESS;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 操作结果
     */
    @Override
    public ServiceResult deleteById(String id) {
        // TODO 添加校验逻辑，如数据权限
        this.cascadeDAO.deleteById(id);
        return CommonResultEnum.SUCCESS;
    }
}
